package huanzhao.erp.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author April
 * 2024/6/28 下午5:08
 * @version 1.0
 */
public class IPUtil {
    /**
     * 判断IP地址是否在CIDR范围内
     *
     * @param ipAddress IP地址
     * @param cidr      CIDR
     * @return boolean
     * 2024/6/28 下午5:09:09
     */
    public static boolean isIpInCidr(String ipAddress, String cidr) throws UnknownHostException {
        // 去除前后的空格
        ipAddress = ipAddress.trim();
        cidr = cidr.trim();
        String[] parts = cidr.split("/");
        String network = parts[0];
        int prefixLength = Integer.parseInt(parts[1]);

        InetAddress inetAddress = InetAddress.getByName(ipAddress);
        InetAddress networkAddress = InetAddress.getByName(network);

        byte[] inetAddressBytes = inetAddress.getAddress();
        byte[] networkAddressBytes = networkAddress.getAddress();

        int mask = 0xffffffff << (32 - prefixLength);

        int ip = bytesToInt(inetAddressBytes);
        int networkIp = bytesToInt(networkAddressBytes);

        return (ip & mask) == (networkIp & mask);
    }

    /**
     * 判断IP地址是否在多个CIDR范围内
     *
     * @param ipAddress IP地址
     * @param cidrs     CIDR数组
     * @return boolean
     * 2024/6/28 下午5:14:32
     */
    public static boolean isIpInCidrs(String ipAddress, String[] cidrs) throws UnknownHostException {
        for (String cidr : cidrs) {
            if (isIpInCidr(ipAddress, cidr)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 将字节数组转换为整数
     *
     * @param bytes 字节数组
     * @return int
     * 2024/6/28 下午5:10:04
     */
    private static int bytesToInt(byte[] bytes) {
        int result = 0;
        for (byte b : bytes) {
            result = (result << 8) | (b & 0xff);
        }
        return result;
    }
}

